<?php

class View_Helper_Truncate extends View_Helper
{

  const BREAK_BEFORE = - 1;

  const BREAK_EXACT = 0;

  const BREAK_AFTER = 1;

  public function execute($string, $length = 80, $trail = '...', $break = self::BREAK_BEFORE, $breakstr = ' .,;-:!?')
  {
    if (strlen(utf8_decode($string)) <= $length) {
      return $string;
    }

    $string = utf8_decode($string);
    $string = strip_tags($string);

    if ($break == self::BREAK_BEFORE) {
      while ($length > 0 && false === strpbrk(substr($string, $length, 1), $breakstr))
        $length --;
    }
    elseif ($break == self::BREAK_AFTER) {
      while ($length < strlen($string) && false === strpbrk(substr($string, $length, 1), $breakstr))
        $length ++;
    }

    $string = substr($string, 0, $length);
    $string .= $trail;
    $string = utf8_encode($string);

    return $string;
  }

}
